/**
* @file live_port.cpp in LiveGraph
* @author linfe
* @comment
* Create on 2022/9/25 22:39
* @version 1.0
**/
#include "LiveProtocol.h"
#include "comm_protocol.h"
#include "comm_crc.h"

#define MAX_LEN_LENGTH 256

#if 0
template<>
LiveData DataHandle<ProtocolAscii>::fromBuffer(QQueue<uint8_t> &buffer) {
    /*split data*/
    uint8_t strbuff[MAX_LEN_LENGTH];
    int i = 0;
    do {
        uint8_t ch = buffer.dequeue();
        strbuff[i++] = ch;
        if (ch == '\n') {
            break;
        }
    } while (!buffer.empty() or i >= MAX_LEN_LENGTH);
    strbuff[i] = '\0';
    /*parse data*/
    LiveData data = {};
    const char *p = (const char *) strbuff;
    char *end = nullptr;
    float f = strtof(++p, &end);
    data.timestamp = f;
    i = 0;
    p = end;
    do {
        f = strtof(++p, &end);
        data.data[i] = f;
        p = strstr(p, ",");
        ++i;
    } while (i < 6);

    return data;
}
#endif

#if 0
template<ProtocolType T>
LiveData DataHandle<T>::handleMsg(uint32_t msg_id, uint8_t *pdata) {
    total_cnt++;
    LiveData out = {0};

    switch (msg_id) {
        case comm_sync_msg_imu_id: {
            auto msg = (comm_sync_msg_imu_t *) pdata;
            valid_cnt++;
            out.is_valid = true;
            out.index = valid_cnt;
            for (int k = 0; k < 3; k++) {
                out.data[k] = 1;//msg->data.acce[k];
                out.data[k + 3] = 2;//msg->data.gyro[k];
            }
            system_time_t *tm = (system_time_t *) &msg->timestamp;
            out.timestamp = (tm->millisecond / 1000 + tm->microsecond / 1.0e6);
        }
            break;
        default:
            break;
    }
    valid_rate = valid_cnt * 100 / total_cnt;
    return out;
}
#endif
#include "cstdio"
#ifndef offsetof
#define offsetof(struct_type, mem_name)      (size_t)&(((struct_type*)0)->mem_name)
#endif

/**
 * 处理一个字符
 * @param dat
 * @return 0: 消息不完整，else: 消息ID
 */
uint32_t DataHandle::updateByte(uint8_t dat) {
    static uint32_t offset = 0;
    auto *pdata = (uint8_t *) data;
    pdata[offset] = dat;
    if (*(uint32_t *) pdata != COMM_SYNC_HEADER) {
        pdata[0] = pdata[1];
        pdata[1] = pdata[2];
        pdata[2] = pdata[3];
        offset = 3;
        return 0;
    }
    if (offset > offsetof(sync_msg_t, data)) {
        uint32_t msg_length = *(uint32_t *) (pdata + offsetof(sync_msg_t, length));
        if (offset >= msg_length) {
            if (crc32_checksum(pdata, msg_length - 4) != 0) {
                offset = 0;
                return 0;
            }
            uint32_t msg_id = *(uint32_t *) (pdata + offsetof(sync_msg_t, msg_id));
            offset = 0;
            return msg_id;
        }
    }
    offset++;
    return 0;
}
uint8_t *DataHandle::buffer() {
    return data;
}

DataHandle::DataHandle() {

}

DataHandle::~DataHandle() {

}

